﻿using System.Collections.Generic;
using org.apache.solr.SolrSharp.Query;
using org.apache.solr.SolrSharp.Query.Parameters;

namespace SolrSharp.Adapters {
	public class SolrQueryBuilder : QueryBuilder, ISolrQueryBuilder {
		private ISolrSearcher searcher;

		public SolrQueryBuilder(Query query, int page, ISolrSearcher searcher) : base(searcher.InnerSearcher) {
			this.searcher = searcher;
			Query = query;
			Page = page;
		}

		public SolrQueryBuilder(Dictionary<string, string> searchkeyvalues, int page, ISolrSearcher searcher)
			: base(searcher.InnerSearcher) {
			this.searcher = searcher;
			Page = page;
			foreach (var pair in searchkeyvalues) {
				AddSearchParameter(pair.Key, pair.Value);
			}
		}

		public SolrQueryBuilder(string[] arKeys, string[] arValues, int page, ISolrSearcher searcher)
			: base(searcher.InnerSearcher) {
			this.searcher = searcher;
			Page = page;
			for (int i = 0; i < arKeys.Length; i++) {
				AddSearchParameter(arKeys[i], arValues[i]);
			}
		}

		public SolrQueryBuilder(string searchterms, int page, ISolrSearcher searcher)
			: base(searcher.InnerSearcher) {
			this.searcher = searcher;
			Page = page;
			AddSearchTerms(searchterms);
		}

		public SolrQueryBuilder InnerQueryBuilder {
			get { return this; }
		}

		private void AddSearchTerms(string searchterms) {
			if (searchterms != null && searchterms != "") {
				var qp = new QueryParameter(SolrSearcher.SolrSchema.DefaultSearchField, searchterms);
				var qpList = new List<QueryParameter> {qp};
				var qps = new QueryParameterCollection("default", qpList);
				Query.AddQueryParameters(qps, ParameterJoin.OR);
			}
		}

		public SolrQueryBuilder(string searchterms, ISolrSearcher searcher)
			: base(searcher.InnerSearcher) {
			this.searcher = searcher;
			AddSearchTerms(searchterms);
		}

		public SolrQueryBuilder(int page, ISolrSearcher searcher)
			: base(searcher.InnerSearcher) {
			this.searcher = searcher;
			Page = page;
		}

		public SolrQueryBuilder(ISolrSearcher searcher) : base(searcher.InnerSearcher) {
			this.searcher = searcher;
		}
	}
}